package com.deyuanyun.pic.settings.support.biz;

import com.deyuanyun.pic.common.cache.TempStoreDataSupport;
import com.deyuanyun.pic.common.spring.SpringAppliction;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.settings.domain.PbfConfigResult;
import com.deyuanyun.pic.settings.domain.base.Code;
import com.deyuanyun.pic.settings.domain.base.UnifiedEncoding;
import com.deyuanyun.pic.settings.mapper.base.UnifiedEncodingMapper;
import com.deyuanyun.pic.settings.service.base.CodeService;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 码表查找封装类
 *
 * User: huanglw
 * Date: 15-8-28 11:32
 * To change this template use File | Settings | File Templates.
 *
 * History: [huanglw][2016-7-4][添加方法：getCodeById(String id)]
 * [huanglw][2016-7-28][添加方法：getNames(String[] ids)]
 */
public class CodeUtil {

    static Logger logger= Logger.getLogger(CodeUtil.class);

    //public static Map codeMap = null;
    //select c.major_code,c.short_name from SYS_BASE_CODE c where c.minor_code is null
    private static ListMultimap<String,Code> menuListMultimap= ArrayListMultimap.create();
    private static final String CODE_DICT_IN_CACHE="APPLICATION.CODE_DICT_IN_CACHE";
    private static final String CODE_DICT_IN_CACHE_LIST="APPLICATION.CODE_DICT_IN_CACHE_LIST";

    /**
     * 得到所有的 码表数据项
     */
    private static void loadAllCode(){
        CodeService codeService= SpringAppliction.getBean(CodeService.class);
        logger.info("加载系统码表参数值");
        List<Code> list = codeService.loadAll();
        menuListMultimap.clear();
        TempStoreDataSupport.removeData(CODE_DICT_IN_CACHE);
        for (Code code : list){
            menuListMultimap.put(code.getMajorCode(),code);
        }
        TempStoreDataSupport.pushDataf(CODE_DICT_IN_CACHE,menuListMultimap);

    }

    /**
     * 手动刷新系统码表参数 map
     *
     * @param flag
     */
    public static void loadCode(boolean flag){
        if (menuListMultimap == null || menuListMultimap.isEmpty()){
            loadAllCode();
        } else if (flag){
            loadAllCode();
        }
    }

    /**
     * 将codeid字段转成codename
     * @param list
     * @param fields
     * @param <T>
     */
    public static<T> void convertId2CodeName(List<T> list,String[] fields) throws Exception{
        loadCode(false);
        for (T t:list){
            for (String fName:fields){
                String id = BeanUtils.getProperty(t,fName);
                if (StringUtils.isBlank(id)){
                    continue;
                }
                String name = getName(id);
                if (StringUtils.isBlank(name)){
                    continue;
                }
                BeanUtils.setProperty(t,fName,name);
            }
        }

    }


    /**
     * 得到码表中的名称
     *
     * @param id 码表Id
     * @return 码表的名称，如果没有该值，返回null对象
     */
    public static String getName(String id){
        Code c=TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST+"_"+id);
        if (c!=null){
            return c.getShortName();
        }

        loadCode(false);
        List<Code> codeList=TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST);
        if (ObjectUtil.isEmptyAll(codeList)){
            codeList=new ArrayList<Code>(menuListMultimap.values());
            TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST,codeList,5);
        }
        for (Code code:codeList){
            if (com.deyuanyun.pic.common.util.StringUtils.isNotNullEmpty(id) && id.equals(code.getId())){

                TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST+"_"+id,code,2);
                return code.getShortName();
            }
        }

        return null;
    }

    public static String getNames(String[] ids){
        if (ObjectUtil.isEmptyAll(ids)) {
            return null;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String id : ids) {
            String codeName = getName(id);
            if (com.deyuanyun.pic.common.util.StringUtils.isNotNullEmpty(codeName)) {
                stringBuilder.append(codeName).append(",");
            }
        }
        if (stringBuilder.length() > 0){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
        }
        return stringBuilder.toString();
    }

    /**
     * 根据的id找到 code对象
     *
     * @param id
     * @return
     */
    public static Code getCodeById(String id){
        if (com.deyuanyun.pic.common.util.StringUtils.isNullEmpty(id)) {
            return null;
        }

        Code c = TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST+"_"+id);
        if (c != null){
            return c;
        }

        loadCode(false);
        List<Code> codeList = TempStoreDataSupport.pullData(CODE_DICT_IN_CACHE_LIST);
        if (ObjectUtil.isEmptyAll(codeList)){
            codeList=new ArrayList<Code>(menuListMultimap.values());
            TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST,codeList,5);
        }

        for (Code code : codeList){
            if (id.equals(code.getId())){
                TempStoreDataSupport.pushDataByIdelTimeMinute(CODE_DICT_IN_CACHE_LIST+"_"+id,code,2);
                return code;
            }
        }

        return null;
    }

    public static List<Code> getCodeList(String majorCode){
        loadCode(false);
        return menuListMultimap.get(majorCode);
    }
    public static List<String> getCodeListString(String majorCode){
        List<String> tl=TempStoreDataSupport.pullData("_getCodeListString_"+majorCode);
        if (ObjectUtil.isNotNullEmpty(tl)){
            return tl;
        }
        loadCode(false);
        List<Code> codeList=menuListMultimap.get(majorCode);
        List<String> s=new ArrayList<String>();
        for (Code code:codeList){
            s.add(code.getShortName());
        }
        TempStoreDataSupport.pushDataByIdelTimeMinute("_getCodeListString_"+majorCode,s,5);
        return s;
    }
    public static List<Code> getCodeList(String majorCode,Short level){
        List<Code> tl=TempStoreDataSupport.pullData("_getCodeList_"+majorCode+"_"+level);
        if (ObjectUtil.isNotNullEmpty(tl)){
            return tl;
        }
        loadCode(false);
        List<Code> codeList=menuListMultimap.get(majorCode);
        List<Code> s=new ArrayList<Code>();
        for (Code code:codeList){//TODO 待处理：无值
            if(code.getLevel() == level){
                s.add(code);
            }
        }
        TempStoreDataSupport.pushDataByIdelTimeMinute("_getCodeList_"+majorCode+"_"+level,s,5);
        return s;
    }

    /**
     * 维修缺陷App字典数据配置专用方法
     * @param majorCode
     * @return
     */
    public static PbfConfigResult getAppCodeList(String majorCode){
        PbfConfigResult tl=TempStoreDataSupport.pullData("_getCodeList_"+majorCode);
        if (ObjectUtil.isNotNullEmpty(tl)){
            return tl;
        }
        loadCode(false);
        List<Code> codeList=menuListMultimap.get(majorCode);
        List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
        for (int i = 0; i <codeList.size() ; i++) {
            if(0!=codeList.get(i).getSort()){//过滤掉--------XXXXXXX-------
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("ID",codeList.get(i).getId());
                map.put("Name",codeList.get(i).getShortName());
                maps.add(map);
            }
        }
        PbfConfigResult pbfConfigResult = new PbfConfigResult();
        pbfConfigResult.setList(maps);
        TempStoreDataSupport.pushDataByIdelTimeMinute("_getCodeList_"+majorCode+"_",pbfConfigResult,5);

        return pbfConfigResult;
    }

    /**
     * 腐蚀控制App字典数据配置专用方法
     * @param majorCode
     * @return
     */
    public static PbfConfigResult getCtrlAppCodeList(String majorCode){
        PbfConfigResult tl=TempStoreDataSupport.pullData("_getCodeList_"+majorCode);
        if (ObjectUtil.isNotNullEmpty(tl)){
            return tl;
        }
        loadCode(false);
        List<Code> codeList=menuListMultimap.get(majorCode);
        List<Map<String,Object>> maps = new ArrayList<Map<String,Object>>();
        for (int i = 0; i <codeList.size() ; i++) {
            if(0!=codeList.get(i).getSort()){//过滤掉--------XXXXXXX-------
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("id",codeList.get(i).getId());
                map.put("name",codeList.get(i).getShortName());
                maps.add(map);
            }
        }
        PbfConfigResult pbfConfigResult = new PbfConfigResult();
        pbfConfigResult.setList(maps);
        TempStoreDataSupport.pushDataByIdelTimeMinute("_getCodeList_"+majorCode+"_",pbfConfigResult,5);

        return pbfConfigResult;
    }

    public static List<Code> getCodeListByParentId(String majorCode,String parentId){
        List<Code> tl=TempStoreDataSupport.pullData("_getCodeListByParentId_"+majorCode+"_"+parentId);
        if (ObjectUtil.isNotNullEmpty(tl)){
            return tl;
        }
        loadCode(false);
        List<Code> codeList=menuListMultimap.get(majorCode);
        List<Code> s=new ArrayList<Code>();
        for (Code code:codeList){
            if(parentId.equals(code.getParentId())){
                s.add(code);
            }
        }
        TempStoreDataSupport.pushDataByIdelTimeMinute("_getCodeListByParentId_"+majorCode+"_"+parentId,s,5);
        return s;
    }
    public static String getCodeId(String majorCode,String name){
    	List<Code> codes=getCodeList(majorCode);
    	for(Code info:codes){
    		if(info.getShortName().equals(name))
    		{
    			return info.getId();
    		}
    	}
        return null;
    }


    //SYS_BASE_UNIFIED_ENCODING  的codeUtil
    private  static  List<UnifiedEncoding> unifiedEncodingList=new ArrayList<UnifiedEncoding>();
    private final static String unifiedEncodingName="Temp_unifiedEncoding_";
    public static void loadCode(){
        if (unifiedEncodingList==null || unifiedEncodingList.isEmpty()){
            UnifiedEncodingMapper dyyPipeLineMapper=SpringAppliction.getBean(UnifiedEncodingMapper.class);
            unifiedEncodingList= dyyPipeLineMapper.findAll();
        }else {
            return;
        }
    }

    /**
     * 根据名称来查找encoding 只会返回第一条 如有企图需求，请另写
     * @param name
     * @return
     */
    public static UnifiedEncoding findEncodByName(String name){
        if (StringUtils.isBlank(name)){return null;}
        UnifiedEncoding t=TempStoreDataSupport.pullData(unifiedEncodingName+name);
        if (t!=null){
            return t;
        }
        loadCode();
        for (UnifiedEncoding encoding:unifiedEncodingList){
            if (name.equals(encoding.getName())){
                TempStoreDataSupport.pushDataByIdelTimeMinute(unifiedEncodingName+name,encoding,2);
                return encoding;
            }
        }
        return null;
    }



}
